package com.mingtu.dzpatrol.activity;

import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.TextView;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.StringUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.dzpatrol.R;
import com.mingtu.dzpatrol.base.BaseActivity;
import com.mingtu.dzpatrol.bean.LoginBean;
import com.mingtu.dzpatrol.bean.UserInfoBean;
import com.mingtu.dzpatrol.callback.ResultCallback;
import com.mingtu.dzpatrol.callback.StringDialogCallback;
import com.mingtu.dzpatrol.utils.Constant;
import com.mingtu.dzpatrol.utils.IntentUtils;
import com.mingtu.dzpatrol.utils.MyLogUtil;
import com.mingtu.dzpatrol.utils.MyToastUtils;
import com.mingtu.dzpatrol.utils.SPTools;
import com.mingtu.dzpatrol.view.MyClearEditText;


import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.edit_account)
    MyClearEditText editAccount;
    @BindView(R.id.edit_password)
    MyClearEditText editPassword;
    @BindView(R.id.button_login)
    Button buttonLogin;
    private String account;
    private String password;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initData() {
        setStatusBarBackground(getResources().getColor(R.color.color_white));
        setTitleBarBackground(getResources().getColor(R.color.color_white));

        hideTopLeftButton();
        setModuleTitle("登录");
        setModuleTitleColor(R.color.text_color333);

        editAccount.setTextLength(20);
        editAccount.setTypeClassTextNumber();
        editPassword.setTypeTextPassword();
        editPassword.getEditText().setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                switch (actionId) {
                    case EditorInfo.IME_ACTION_DONE:
                        login();
                        break;
                }
                return true;
            }
        });
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void getData() {

    }

    @OnClick(R.id.button_login)
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.button_login:
                login();
                break;
        }
    }

    /**
     * 登录(此处的登录逻辑，是为了用户离线登录之后，重新联网之后使用)
     */
    private void login() {
        account = editAccount.getText().toString().trim();
        password = editPassword.getText().toString().trim();

        if (StringUtils.isEmpty(account)) {
            MyToastUtils.showInfo("请输入账号！");
            return;
        }

        if (StringUtils.isEmpty(password)) {
            MyToastUtils.showInfo("请输入密码！");
            return;
        }

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("mobile", account);
        hashMap.put("password", password);
        hashMap.put("loginType", Constant.LOGIN_TYPE);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(Constant.getInstance().POST_LOGIN)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            LoginBean loginBean = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                loginBean = new LoginBean();
                                loginBean = gson.fromJson(result, LoginBean.class);
                                String token = loginBean.getToken();

                                SPStaticUtils.put(SPTools.token, token);
                                SPStaticUtils.put(SPTools.account, account);

                                getUserInfo(new ResultCallback() {
                                    @Override
                                    public void result(Object object) {
                                        if (Boolean.parseBoolean(object.toString())) {
                                            IntentUtils.getInstance().readyGoThenKill(LoginActivity.this, MainActivity.class);
                                        } else {
                                            MyToastUtils.showInfo("用户信息获取失败！");
                                        }
                                    }
                                });


                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }

                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);
                    }
                });
    }

    /**
     * 获取用户信息
     */
    private void getUserInfo(ResultCallback resultCallback) {

        OkGo.<String>get(Constant.getInstance().GET_USER_INFO)
                .tag(this)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                UserInfoBean userInfoBean = new UserInfoBean();
                                userInfoBean = gson.fromJson(result, UserInfoBean.class);

                                UserInfoBean.UserBean userBean = userInfoBean.getUser();
                                String name = userBean.getName();
                                String username = userBean.getUsername();
                                String userId = userBean.getUserId();
                                String mobile = userBean.getMobile();
                                String deptName = userBean.getDeptName();

                                if (!StringUtils.isEmpty(mobile)) {
                                    SPStaticUtils.put(SPTools.mobile, mobile);//保存手机号
                                } else {
                                    SPStaticUtils.put(SPTools.mobile, "");
                                }

                                if (!StringUtils.isEmpty(deptName)) {
                                    SPStaticUtils.put(SPTools.deptName, deptName); //所属部门
                                } else {
                                    SPStaticUtils.put(SPTools.deptName, "");
                                }


                                if (!StringUtils.isEmpty(name)) {
                                    SPStaticUtils.put(SPTools.userName, name);//保存用户名
                                    SPStaticUtils.put(SPTools.userId, userId);//保存userId
                                    resultCallback.result(true);
                                } else {
                                    resultCallback.result(false);
                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }

                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);
                    }
                });


    }


}